<?php

namespace app\api\controller;

use app\common\controller\Api;
use Hedeqiang\TenIM\IM;
use think\Db;
use think\Cache;
/**
 * 抖音测试接口
 */
class Dypay extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    function getByteAuthorization($privateKeyStr, $data, $appId, $nonceStr, $timestamp, $keyVersion) {
		$byteAuthorization = '';
		// 读取私钥
		$privateKey = openssl_pkey_get_private($privateKeyStr);
			if (!$privateKey) {
				throw new InvalidArgumentException("Invalid private key");
			}
		// 生成签名
		$signature = $this->getSignature("POST", "/requestOrder", $timestamp, $nonceStr, $data, $privateKey);
		if ($signature === false) {
			return null;
		}
		// 构造 byteAuthorization
		$byteAuthorization = sprintf("SHA256-RSA2048 appid=%s,nonce_str=%s,timestamp=%s,key_version=%s,signature=%s", $appId, $nonceStr, $timestamp, $keyVersion, $signature);
		return $byteAuthorization;
	}

	function getSignature($method, $url, $timestamp, $nonce, $data, $privateKey) {
		// printf("method:%s\n url:%s\n timestamp:%s\n nonce:%s\n data:%s", $method, $url, $timestamp, $nonce, $data);
		$targetStr = $method. "\n" . $url. "\n" . $timestamp. "\n" . $nonce. "\n" . $data. "\n";
		openssl_sign($targetStr, $sign, $privateKey, OPENSSL_ALGO_SHA256);
		$sign = base64_encode($sign);
		return $sign;
	}

	function randStr($length = 8) {
		$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
		$str = '';
		for ($i = 0; $i < $length; $i++) {
			$str .= $chars[mt_rand(0, strlen($chars) - 1)];
		}
		return $str;
	}
	public function csdy(){
        $system_recharge_id = $this->request->post('system_recharge_id');
        $type = $this->request->post('type')?$this->request->post('type'):1;
        $device_type = $this->request->post('device_type')?$this->request->post('device_type'):1;
        
        if (empty($system_recharge_id)) {
            $this->error("请选择充值配置");
        }
        $system_recharge = DB::name("system_recharge")->where("id",$system_recharge_id)->find();
        if(empty($system_recharge)){
            $this->error("充值配置有误");
        }
        $order_no = "recharge".date("YmdHis").rand(1000,9999);
        // $data = array(
        //     "user_id" => $this->auth->id,
        //     "order_no" => $order_no,
        //     "money" => $system_recharge['money'],
        //     "dou_money" => $system_recharge['dou_money'],
        //     "create_time" => date("Y-m-d H:i:s")
        // );
        $user_find = DB::name("user")->where("id",$this->auth->id)->find();
        if($user_find['share_type'] == 888){
            $share_type = 999;
        }else{
            $share_type = $user_find['share_type'];
        }
        
        if($type == 1 && $device_type == 1){
            //虚拟支付
            // 如果是基础库的wx.requestVirtualPayment，uri固定为requestVirtualPayment
            // $uri = '/xpay/query_user_balance';
            // 此处appkey为假设值，实际使用应根据支付环境(env参数)替换为对应的AppKey
            $appkey = "SgM7386iqymWi0qrj7ReIn7CbgRqLjBA";
            $offerId = '1450217770';
            // $ip = $_SERVER['REMOTE_ADDR'];
            // $data = array(
            //     "openid" => $user_find['openid'],
            //     "env" => 1,
            //     "user_ip" => $ip,
            // );
            // $post_body = json_encode($data);
            // $pay_sig = $this->calc_pay_sig($uri, $post_body, $appkey);
            
            // $signature = $this->calc_signature($post_body, $user_find['session_key']);

            // $access_token = $this->get_access_token();
            // // print_r($access_token);exit;
            // $url = 'https://api.weixin.qq.com/xpay/query_user_balance?access_token='.$access_token.'&pay_sig='.$pay_sig.'&signature='.$signature;
            
            // $res = json_decode($this->json_post($url,$data),true);
            // if($res['errcode'] != 0){
            //     $this->error($res['errmsg']);
            // }else{
                // $balance = $res['balance']/100;
                // if($balance >= $system_recharge['money']){
                //     //余额足够
                //     $result = array(
                //         "pay_status" =>1
                //     );
                //     $this->success("没搞完，别瞎测",$result);
                // }else{
                     // 如果是基础库的wx.requestVirtualPayment，uri固定为requestVirtualPayment
                     $uri = 'requestVirtualPayment';
                     // 此处appkey为假设值，实际使用应根据支付环境(env参数)替换为对应的AppKey
                     $data = array(
                         "offerId" => $offerId,
                         "buyQuantity" => $system_recharge['money']*10*10,
                        //  "buyQuantity" => 1,
                         "env" => 0,
                         "currencyType" => "CNY",
                         "outTradeNo" => $order_no,
                         "attach" => "testdata",
                     );
                    //  $this->error($data);
                     $post_body = json_encode($data);
                     $pay_sig = $this->calc_pay_sig($uri, $post_body, $appkey);
                     $signature = $this->calc_signature($post_body, $user_find['session_key']);
                    //余额不足
                    $data = array(
                        "user_id" => $this->auth->id,
                        "pid" => $user_find['pid'],
                        "user_channel_id" => $user_find['user_channel_id'],
                        "share_type" => $share_type,
                        "order_no" => $order_no,
                        "money" => $system_recharge['money'],
                        "device_type" => $device_type,
                        "dou_money" => $system_recharge['dou_money'],
                        "create_time" => date("Y-m-d H:i:s")
                    );
                    DB::name("user_recharge")->insert($data);
                    
                    $result = array(
                        "pay_status" => 2,
                        "order_id" => $order_no,
                        "buyQuantity" => $system_recharge['money']*10*10,
                        "signature" => $signature,
                        "pay_sig" => $pay_sig
                    );
                file_put_contents("log/xuni_pay".date('Ymd').".txt","pay_sig=".$pay_sig.PHP_EOL,FILE_APPEND);

                    $this->success("提交成功",$result);
                // }
            // }
        }else if($type == 1 && ($device_type == 2 || $device_type == 3)){
            $data = array(
                "user_id" => $this->auth->id,
                "pid" => $user_find['pid'],
                "user_channel_id" => $user_find['user_channel_id'],
                "share_type" => $share_type,
                "order_no" => $order_no,
                "money" => $system_recharge['money'],
                "device_type" => $device_type,
                "dou_money" => $system_recharge['dou_money'],
                "create_time" => date("Y-m-d H:i:s")
            );
            
            DB::name("user_recharge")->insert($data);
            
            $user_info = DB::name("user")->where("id",$this->auth->id)->find();
            $openid = $user_info['openid'];
            $method = 'miniapp'; //小程序支付
            $type = 'wechat';
            $title = "购买商品";
            //回调链接
            $notifyurl = $this->request->root(true) . '/addons/epay/index/notifyOrder/paytype/' . $type;
            $returnurl = $this->request->root(true) . '/h5/#/index/index';
            $response = Service::submitOrder($data['money'], $order_no, $type, $title, $notifyurl, $returnurl, $method, $openid);

            file_put_contents("log/xuni_pay".date('Ymd').".txt","response=".json_encode($response).PHP_EOL,FILE_APPEND);
            $this->success("发起充值成功", $response);
        }if($type == 2 && $device_type == 1){
            $data = array(
                "user_id" => $this->auth->id,
                "pid" => $user_find['pid'],
                "user_channel_id" => $user_find['user_channel_id'],
                "share_type" => $share_type,
                "order_no" => $order_no,
                "type" => $type,
                "money" => $system_recharge['money'],
                "device_type" => $device_type,
                "dou_money" => $system_recharge['dou_money'],
                "create_time" => date("Y-m-d H:i:s")
            );
            
            DB::name("user_recharge")->insert($data);
            // 请求时间戳
            $timestamp = time();
            // 开发者填入自己的小程序 app_id
            $appId = "tte3e2955f7cd2a7d301";
            // 随机字符串
            $nonceStr = $this->randStr(10);
            // 应用公钥版本,每次重新上传公钥后需要更新,可通过「开发管理-开发设置-密钥设置」处获取
            $keyVersion = "1";
            // 应用私钥,用于加签 重要：1.测试时请修改为开发者自行生成的私钥;2.请勿将示例密钥用于生产环境;3.建议开发者不要将私钥文本写在代码中
            $privateKeyStr = file_get_contents("../addons/epay/certs/privatekey.pem");
            // 生成好的 data  
            $skuId = $system_recharge_id;	//外部商品id，如：号卡商品id、会员充值套餐id、某类服务id、付费工具id等
            $price = 1;	//价格 单位：分
            $quantity = 1;	//购买数量	0 < quantity <= 100 
            $title = "充值";	//商品标题，长度 <= 256字节
            $imageList = "";	//商品图片链接，长度 <= 512 字节注意：目前只支持传入一项
            $goods_type = 401;	//商品类型
            $tagGroupId = "tag_group_7272625659888041996";	//交易规则标签组
            $outOrderNo = $order_no;	//外部订单号
            $payExpireSeconds = 3000;	//支付超时时间，单位秒，例如 300 表示 300 秒后过期；不传或传 0 会使用默认值 300，不能超过48小时。
            $orderEntrySchema = "";	//订单详情页
            $data = json_encode(array(
                "skuList" => array(array(
                    "skuId" => "$skuId",
                    "price" => $price,
                    "quantity" => $quantity,
                    "title" => $title,
                    "imageList" => ['https://shsh.vxmeng.com/static/dy_recharge.png'],
                    "type" => $goods_type,
                    "tagGroupId" => $tagGroupId,
                )),
                "outOrderNo" => $outOrderNo,
                "totalAmount" => $price,
                "limitPayWayList" => array(),
                "payExpireSeconds" => $payExpireSeconds,
                "orderEntrySchema" => array("path"=>"pages/index/index","params"=>json_encode(array("recharge_id"=>"$skuId")))
            ),JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
            // $data = "{\"skuList\":[{\"skuId\":\"1\",\"price\":9999,\"quantity\":1,\"title\":\"标题\",\"imageList\":[\"https://shsh.vxmeng.com/static/dy_recharge.png\"],\"type\":401,\"tagGroupId\":\"idxxx\"}],\"outOrderNo\":\"1213\",\"totalAmount\":9999,\"limitPayWayList\":[],\"payExpireSeconds\":3000,\"orderEntrySchema\":{\"path\":\"page/index/index\",\"params\":\"{\\\"poi\\\":\\\"6601248937917548558\\\",\\\"aweme_useTemplate\\\":1}\"}}";

            $byteAuthorization = $this->getByteAuthorization($privateKeyStr, $data, $appId, $nonceStr, $timestamp, $keyVersion);
            $result = array(
                "data_value" => $data,
                "byteAuthorization_value" => $byteAuthorization
            );
            $this->success('发起充值成功',$result);
        }else{
            $this->success("暂无充值方式");
        }
    }

    
    
}
